R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.

When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

In this portfolio I was very interested in maps again. I used a training I found online on how to make maps using tmap rather than the ggplot version. I went through the training first (it gave direct code for different things) and then tried to extend what I learned onto new data sets. However, I had a lot of trouble adding in new variables. I’ll need to do some more work to figure out how to do that.

library(sf)
## Linking to GEOS 3.9.1, GDAL 3.4.0, PROJ 8.1.1; sf_use_s2() is TRUE
library(raster)
## Loading required package: sp
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:raster':
## 
##     intersect, select, union
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(spData)
library(spDataLarge)
## Warning: package 'spDataLarge' was built under R version 4.1.3
library(tidyverse)
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.1 ──
## ✓ ggplot2 3.3.5     ✓ purrr   0.3.4
## ✓ tibble  3.1.6     ✓ stringr 1.4.0
## ✓ tidyr   1.1.4     ✓ forcats 0.5.1
## ✓ readr   2.1.1
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## x tidyr::extract() masks raster::extract()
## x dplyr::filter()  masks stats::filter()
## x dplyr::lag()     masks stats::lag()
## x dplyr::select()  masks raster::select()
library(tmap)    # for static and interactive maps
library(leaflet) # for interactive maps
library(ggplot2) 
library(mapview)
# Add fill layer to nz shape
tm_shape(nz) +
  tm_fill() 

# Add border layer to nz shape
tm_shape(nz) +
  tm_borders() 

# Add fill and border layers to nz shape
tm_shape(nz) +
  tm_fill() +
  tm_borders() 

map_nz = tm_shape(nz) + tm_polygons()
class(map_nz)
## [1] "tmap"
#> [1] "tmap"
map_nz1 = map_nz +
  tm_shape(nz_elev) + tm_raster(alpha = 0.7)

map_nz1
## stars object downsampled to 877 by 1140 cells. See tm_shape manual (argument raster.downsample)

urb_1970_2030 = urban_agglomerations %>% 
  filter(year %in% c(1970, 1990, 2010, 2030))

tm_shape(world) +
  tm_polygons() +
  tm_shape(urb_1970_2030) +
  tm_symbols(col = "black", border.col = "white", size = "population_millions") +
  tm_facets(by = "year", nrow = 2, free.coords = FALSE)

For some reason this gif did not work. I can’t figure out where I am going wrong.

urb_anim = tm_shape(world) +
  tm_polygons() +
  tm_shape(urb_1970_2030) +
  tm_symbols(col = "black", border.col = "white", size = "population_millions") +
  tm_facets(along = "year", free.coords = FALSE)

tmap_animation(urb_anim, filename = "urb_anim2.gif", width = 5 , height = 5 , delay = 25)
## Creating frames
## ========================================
## ====================
## ====================
## 
## Creating animation
## Animation saved to /Users/elaynaseago/Downloads/R_Class/portfolio-10/urb_anim2.gif
urb_anim = tm_shape(world) + tm_polygons() + 
  tm_shape(urban_agglomerations) + tm_dots(size = "population_millions") +
  tm_facets(along = "year", free.coords = FALSE)

tmap_animation(urb_anim, filename = "urb_anim.gif", delay = 25)
## Creating frames
## =========
## ====
## =====
## ====
## =====
## ====
## =====
## ====
## ====
## =====
## ====
## =====
## ====
## =====
## ====
## =====
## ====
## 
## Creating animation
## Animation saved to /Users/elaynaseago/Downloads/R_Class/portfolio-10/urb_anim.gif
tmap_mode("view")
## tmap mode set to interactive viewing
map_nz
mapview::mapview(nz)
library(mapdeck)
## 
## Attaching package: 'mapdeck'
## The following object is masked from 'package:tibble':
## 
##     add_column
set_token(Sys.getenv("MAPBOX"))
crash_data = read.csv("https://git.io/geocompr-mapdeck")
crash_data = na.omit(crash_data)
ms = mapdeck_style("dark")
mapdeck(style = ms, pitch = 45, location = c(0, 52), zoom = 4) %>%
add_grid(data = crash_data, lat = "lat", lon = "lng", cell_size = 1000,
         elevation_scale = 50, layer_id = "grid_layer",
         colour_range = viridisLite::plasma(6))
## Registered S3 method overwritten by 'jsonify':
##   method     from    
##   print.json jsonlite
library(shiny)    # for shiny apps
library(leaflet)  # renderLeaflet function
library(spData)   # loads the world dataset 
ui = fluidPage(
  sliderInput(inputId = "life", "Life expectancy", 49, 84, value = 80),
      leafletOutput(outputId = "map")
  )
server = function(input, output) {
  output$map = renderLeaflet({
    leaflet() %>% 
      # addProviderTiles("OpenStreetMap.BlackAndWhite") %>%
      addPolygons(data = world[world$lifeExp < input$life, ])})
}

End of the tutorial, beginning of trying to extend!

urban_agglomerations
## Simple feature collection with 540 features and 9 fields
## Geometry type: POINT
## Dimension:     XY
## Bounding box:  xmin: -118.2417 ymin: -34.60508 xmax: 139.6917 ymax: 55.755
## Geodetic CRS:  WGS 84
## # A tibble: 540 × 10
##    index  year `rank\norder` `country\ncode` country_or_area city_code
##    <dbl> <dbl>         <dbl>           <dbl> <chr>               <dbl>
##  1     1  1950             6              32 Argentina           20058
##  2     2  1955             5              32 Argentina           20058
##  3     3  1960             6              32 Argentina           20058
##  4     4  1965             5              32 Argentina           20058
##  5     5  1970             5              32 Argentina           20058
##  6     6  1975             6              32 Argentina           20058
##  7     7  1980             6              32 Argentina           20058
##  8     8  1985             7              32 Argentina           20058
##  9     9  1990             7              32 Argentina           20058
## 10    10  1995            10              32 Argentina           20058
## # … with 530 more rows, and 4 more variables: urban_agglomeration <chr>,
## #   note <dbl>, population_millions <dbl>, geometry <POINT [°]>
shp <- st_read("acs_2012_2016_county_us_B27001/acs_2012_2016_county_us_B27001.shp")
## Reading layer `acs_2012_2016_county_us_B27001' from data source 
##   `/Users/elaynaseago/Downloads/R_Class/portfolio-10/acs_2012_2016_county_us_B27001/acs_2012_2016_county_us_B27001.shp' 
##   using driver `ESRI Shapefile'
## Simple feature collection with 3141 features and 5 fields
## Geometry type: MULTIPOLYGON
## Dimension:     XY
## Bounding box:  xmin: -2031905 ymin: -2427680 xmax: 2516374 ymax: 732103.3
## Projected CRS: Lambert_Azimuthal_Equal_Area
tm_shape(shp)+
  tm_polygons()+
  tmap_options(check.and.fix = TRUE)
## Warning: The shape shp is invalid (after reprojection). See sf::st_is_valid

I’m not sure why the whole world is showing up, it makes shifting Alaska in not make sense.

tm_shape(shp)+
  tm_polygons("un_2012")+
  tmap_options(check.and.fix = TRUE)
## Warning: The shape shp is invalid (after reprojection). See sf::st_is_valid
tm_shape(shp)+
  tm_bubbles("un_2012")
## Warning: The shape shp is invalid (after reprojection). See sf::st_is_valid
## Legend for symbol sizes not available in view mode.
colony <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2022/2022-01-11/colony.csv')
## Rows: 1222 Columns: 10
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (2): months, state
## dbl (8): year, colony_n, colony_max, colony_lost, colony_lost_pct, colony_ad...
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
stressor <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2022/2022-01-11/stressor.csv')
## Rows: 7332 Columns: 5
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (3): months, state, stressor
## dbl (2): year, stress_pct
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
colony_jan_2015 <- colony %>% 
  filter(
    year == "2015" ,
    months == "January-March" ,
    state != "Other States" ,
    state != "United States"
  )

colony_jan_2015
## # A tibble: 45 × 10
##     year months        state     colony_n colony_max colony_lost colony_lost_pct
##    <dbl> <chr>         <chr>        <dbl>      <dbl>       <dbl>           <dbl>
##  1  2015 January-March Alabama       7000       7000        1800              26
##  2  2015 January-March Arizona      35000      35000        4600              13
##  3  2015 January-March Arkansas     13000      14000        1500              11
##  4  2015 January-March Californ…  1440000    1690000      255000              15
##  5  2015 January-March Colorado      3500      12500        1500              12
##  6  2015 January-March Connecti…     3900       3900         870              22
##  7  2015 January-March Florida     305000     315000       42000              13
##  8  2015 January-March Georgia     104000     105000       14500              14
##  9  2015 January-March Hawaii       10500      10500         380               4
## 10  2015 January-March Idaho        81000      88000        3700               4
## # … with 35 more rows, and 3 more variables: colony_added <dbl>,
## #   colony_reno <dbl>, colony_reno_pct <dbl>
shp
## Simple feature collection with 3141 features and 5 fields
## Geometry type: MULTIPOLYGON
## Dimension:     XY
## Bounding box:  xmin: -2031905 ymin: -2427680 xmax: 2516374 ymax: 732103.3
## Projected CRS: Lambert_Azimuthal_Equal_Area
## First 10 features:
##    GEOID                     NAME  un_2012  un_2016     unnsrd_
## 1  01001  Autauga County, Alabama 21.41164 17.49956  -3.9120806
## 2  01003  Baldwin County, Alabama 32.05542 25.92662  -6.1288013
## 3  01005  Barbour County, Alabama 38.05556 30.10408  -7.9514723
## 4  01007     Bibb County, Alabama 32.98112 16.71588 -16.2652396
## 5  01009   Blount County, Alabama 27.25213 20.36988  -6.8822581
## 6  01011  Bullock County, Alabama 20.40100 34.53271  14.1317078
## 7  01013   Butler County, Alabama 34.79951 25.96323  -8.8362805
## 8  01015  Calhoun County, Alabama 28.40327 21.27503  -7.1282349
## 9  01017 Chambers County, Alabama 34.99696 25.41592  -9.5810328
## 10 01019 Cherokee County, Alabama 20.39887 19.69732  -0.7015503
##                          geometry
## 1  MULTIPOLYGON (((1269841 -13...
## 2  MULTIPOLYGON (((1185877 -14...
## 3  MULTIPOLYGON (((1408481 -13...
## 4  MULTIPOLYGON (((1176099 -12...
## 5  MULTIPOLYGON (((1240383 -11...
## 6  MULTIPOLYGON (((1374118 -13...
## 7  MULTIPOLYGON (((1263079 -13...
## 8  MULTIPOLYGON (((1281286 -11...
## 9  MULTIPOLYGON (((1382944 -12...
## 10 MULTIPOLYGON (((1324976 -10...
colony_jan_2015
## # A tibble: 45 × 10
##     year months        state     colony_n colony_max colony_lost colony_lost_pct
##    <dbl> <chr>         <chr>        <dbl>      <dbl>       <dbl>           <dbl>
##  1  2015 January-March Alabama       7000       7000        1800              26
##  2  2015 January-March Arizona      35000      35000        4600              13
##  3  2015 January-March Arkansas     13000      14000        1500              11
##  4  2015 January-March Californ…  1440000    1690000      255000              15
##  5  2015 January-March Colorado      3500      12500        1500              12
##  6  2015 January-March Connecti…     3900       3900         870              22
##  7  2015 January-March Florida     305000     315000       42000              13
##  8  2015 January-March Georgia     104000     105000       14500              14
##  9  2015 January-March Hawaii       10500      10500         380               4
## 10  2015 January-March Idaho        81000      88000        3700               4
## # … with 35 more rows, and 3 more variables: colony_added <dbl>,
## #   colony_reno <dbl>, colony_reno_pct <dbl>
SHP <- as_tibble(shp)
SHP
## # A tibble: 3,141 × 6
##    GEOID NAME       un_2012 un_2016 unnsrd_                             geometry
##    <chr> <chr>        <dbl>   <dbl>   <dbl>                   <MULTIPOLYGON [m]>
##  1 01001 Autauga C…    21.4    17.5  -3.91  (((1269841 -1303980, 1248372 -13008…
##  2 01003 Baldwin C…    32.1    25.9  -6.13  (((1185877 -1467641, 1186625 -14698…
##  3 01005 Barbour C…    38.1    30.1  -7.95  (((1408481 -1312269, 1409678 -13164…
##  4 01007 Bibb Coun…    33.0    16.7 -16.3   (((1176099 -1258997, 1175793 -12558…
##  5 01009 Blount Co…    27.3    20.4  -6.88  (((1240383 -1149119, 1222632 -11434…
##  6 01011 Bullock C…    20.4    34.5  14.1   (((1374118 -1308871, 1374590 -13236…
##  7 01013 Butler Co…    34.8    26.0  -8.84  (((1263079 -1397063, 1250096 -13989…
##  8 01015 Calhoun C…    28.4    21.3  -7.13  (((1281286 -1152171, 1289206 -11413…
##  9 01017 Chambers …    35.0    25.4  -9.58  (((1382944 -1225846, 1390214 -12356…
## 10 01019 Cherokee …    20.4    19.7  -0.702 (((1324976 -1050279, 1325603 -10520…
## # … with 3,131 more rows
newSHP <- SHP %>% 
  separate(NAME , sep = "," , into = c("county" , "state"))

newSHP
## # A tibble: 3,141 × 7
##    GEOID county          state un_2012 un_2016 unnsrd_                  geometry
##    <chr> <chr>           <chr>   <dbl>   <dbl>   <dbl>        <MULTIPOLYGON [m]>
##  1 01001 Autauga County  " Al…    21.4    17.5  -3.91  (((1269841 -1303980, 124…
##  2 01003 Baldwin County  " Al…    32.1    25.9  -6.13  (((1185877 -1467641, 118…
##  3 01005 Barbour County  " Al…    38.1    30.1  -7.95  (((1408481 -1312269, 140…
##  4 01007 Bibb County     " Al…    33.0    16.7 -16.3   (((1176099 -1258997, 117…
##  5 01009 Blount County   " Al…    27.3    20.4  -6.88  (((1240383 -1149119, 122…
##  6 01011 Bullock County  " Al…    20.4    34.5  14.1   (((1374118 -1308871, 137…
##  7 01013 Butler County   " Al…    34.8    26.0  -8.84  (((1263079 -1397063, 125…
##  8 01015 Calhoun County  " Al…    28.4    21.3  -7.13  (((1281286 -1152171, 128…
##  9 01017 Chambers County " Al…    35.0    25.4  -9.58  (((1382944 -1225846, 139…
## 10 01019 Cherokee County " Al…    20.4    19.7  -0.702 (((1324976 -1050279, 132…
## # … with 3,131 more rows
  SHP_colony <- full_join(
    colony_jan_2015 ,
    newSHP ,
    by = "state" ,
    
  )
SHP_colony
## # A tibble: 3,186 × 16
##     year months        state     colony_n colony_max colony_lost colony_lost_pct
##    <dbl> <chr>         <chr>        <dbl>      <dbl>       <dbl>           <dbl>
##  1  2015 January-March Alabama       7000       7000        1800              26
##  2  2015 January-March Arizona      35000      35000        4600              13
##  3  2015 January-March Arkansas     13000      14000        1500              11
##  4  2015 January-March Californ…  1440000    1690000      255000              15
##  5  2015 January-March Colorado      3500      12500        1500              12
##  6  2015 January-March Connecti…     3900       3900         870              22
##  7  2015 January-March Florida     305000     315000       42000              13
##  8  2015 January-March Georgia     104000     105000       14500              14
##  9  2015 January-March Hawaii       10500      10500         380               4
## 10  2015 January-March Idaho        81000      88000        3700               4
## # … with 3,176 more rows, and 9 more variables: colony_added <dbl>,
## #   colony_reno <dbl>, colony_reno_pct <dbl>, GEOID <chr>, county <chr>,
## #   un_2012 <dbl>, un_2016 <dbl>, unnsrd_ <dbl>, geometry <MULTIPOLYGON [m]>